package appapi.service.impl;

import appapi.Global.BusinessException;
import appapi.Request.Basic.DelEquipImportReq;
import appapi.Request.Basic.GetEquipImportReq;
import appapi.Request.EquiPageReq;
import appapi.Request.EquipmentPageReq;
import appapi.Request.ProjPageReq;
import appapi.Request.SaveImportReq;
import appapi.Request.record.BindEquipmentReq;
import appapi.Vo.AppVo.ExcelEquipVo;
import appapi.Vo.AppVo.ExecelEquipVos;
import appapi.Vo.AppVo.GetEquipList;
import appapi.Vo.UpdateImportEquipVo;
import appapi.config.CurrentUser;
import appapi.dao.*;
import appapi.dto.AnnexType;
import appapi.dto.WxCodeDto;
import appapi.dto.EquipmentEnum;
import appapi.dto.basic.EquipNoDto;
import appapi.dto.basic.GenerateImportDto;
import appapi.entity.Zhongjiao.AnnexDto;
import appapi.entity.Zhongjiao.DictionaryDto;
import appapi.dto.EquiPageReqModel;
import appapi.entity.Zhongjiao.EquipmentDto;
import appapi.entity.Zhongjiao.ProjectDto;
import appapi.entity.app.AnnexEntity;
import appapi.entity.basic.*;
import appapi.service.IEquipmentService;
import appapi.utils.OrderUtils;
import appapi.utils.RedisUtils;
import appapi.utils.WeChatUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.util.concurrent.AtomicDouble;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author djq
 * @date 2023/5/16 15:15
 * @description:
 */
@Component
public class EquipmentService<EquipType> implements IEquipmentService {
    @Resource
    private EquipmentMapper equipmentMapper;
    @Resource
    private EquipextendMapper equipextendMapper;
    @Autowired
    private AnnexMapper annexMapper;
    @Resource
    ProjectMapper projectMapper;
    @Resource
    EquipmaintenanitemMapper equipmaintenanitemMapper;
    @Resource
    MaintenanitemMapper maintenanitemMapper;
    @Resource
    DictionaryMapper dictionaryMapper;
    @Resource
    EquipmenttypeMapper equipmenttypeMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private StaffMapper staffMapper;
    @Resource
    SelfcheckitemMapper selfcheckitemMapper;
    @Resource
    EquipselfcheckitemMapper equipselfcheckitemMapper;
    @Value("${web.image-path}")
    private String visitPath;
    @Value("${web.upload-path}")
    private String uploadDir;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void InsertEquipment(EquipmentDto dto) {

        checkProj(dto);
        dto.setCreateTime(LocalDateTime.now());
        dto.setUpdateTime(LocalDateTime.now());
        int iRet = equipmentMapper.insertSelective(dto);
        if (iRet > 0) {
            //添加设备扩展信息
            String json = JSON.toJSONString(dto);
            EquipextendEntity extend = JSON.parseObject(json, new TypeReference<EquipextendEntity>() {
            });
            Long equipId = dto.getEquipId();
            extend.setEquipId(equipId);
            equipextendMapper.insertSelective(extend);
            //添加附件
            if (dto.getAnnexUrl() != null) {
                List<AnnexEntity> annexCollect = dto.getAnnexUrl().stream().map(annex -> {
                    AnnexEntity entity = new AnnexEntity();
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateTime(LocalDateTime.now());
                    entity.setAnnexTitle("设备进场");
                    entity.setAnnexType(AnnexType.AnnexTypeEnum.mobilization.name());
                    entity.setAnnexUrl(annex);
                    entity.setCreateUser(dto.getCreateUser());
                    entity.setRecId(equipId);
                    return entity;
                }).collect(Collectors.toList());
                if (annexCollect.size() > 0) {
                    annexMapper.insertList(annexCollect);
                }
            }
        }

        //新增设备-维保项目
        addMaintenanitem(dto);

        //新增设备-自检项目
        addSelfItem(dto);


    }

    private void addSelfItem(EquipmentDto dto) {
        //查到该设备类型预置的自检项目
        List<SelfcheckItemEntity> selfList = selfcheckitemMapper.selectItemByTypeId(dto.getEquipTypeId());
        List<EquipselfcheckitemEntity> selfCollect = selfList.stream().map(map -> {
            EquipselfcheckitemEntity entity = new EquipselfcheckitemEntity();
            entity.setItemName(map.getItemName());
            entity.setItemDesc(map.getItemDesc());
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
            entity.setEquipId(dto.getEquipId());
            return entity;
        }).collect(Collectors.toList());
        //新增设备-自检项目
        if (selfCollect.size() > 0) {
            equipselfcheckitemMapper.insertBatch(selfCollect);
        }
    }

    private void addMaintenanitem(EquipmentDto dto) {
        //查到该设备类型预置的维保项目
        List<Map<String, Object>> list = maintenanitemMapper.selectEquipTypeId(dto.getEquipTypeId());
        List<EquipmaintenanitemEntity> collect = list.stream().map(map -> {
            EquipmaintenanitemEntity entity = new EquipmaintenanitemEntity();
            entity.setItemName(map.get("itemName").toString());
            entity.setItemDesc(map.get("itemDesc").toString());
            entity.setCreateTime(LocalDateTime.now());
            entity.setUpdateTime(LocalDateTime.now());
            entity.setEquipId(dto.getEquipId());
            return entity;
        }).collect(Collectors.toList());
        //新增设备-维保项目
        if (collect.size() > 0) {
            equipmaintenanitemMapper.insertList(collect);
        }
    }

    @Override
    public void UpdateEquipment(EquipmentDto dto) {

        checkProj(dto);
        int iRet = equipmentMapper.updateByPrimaryKeySelective(dto);
        if (iRet > 0) {
            //更新设备扩展信息
            String json = JSON.toJSONString(dto);
            EquipextendEntity extend = JSON.parseObject(json, new TypeReference<EquipextendEntity>() {
            });
            Long equipId = dto.getEquipId();
            extend.setEquipId(equipId);
            equipextendMapper.updateByPrimaryKeySelective(extend);
            //设备附件
            List<Long> equipIds = new ArrayList<>();
            equipIds.add(dto.getEquipId());
            //删除设备原有附件记录
            annexMapper.deleteByRecId(AnnexType.AnnexTypeEnum.mobilization.name(), equipIds);
            //添加记录
            if (dto.getAnnexUrl() != null && dto.getAnnexUrl().size() > 0) {
                List<AnnexEntity> annexCollect = dto.getAnnexUrl().stream().map(annex -> {
                    AnnexEntity entity = new AnnexEntity();
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateTime(LocalDateTime.now());
                    entity.setAnnexTitle("设备进场");
                    entity.setAnnexType(AnnexType.AnnexTypeEnum.mobilization.name());
                    entity.setAnnexUrl(annex);
                    entity.setCreateUser(dto.getCreateUser());
                    entity.setRecId(equipIds.get(0));
                    return entity;
                }).collect(Collectors.toList());
                annexMapper.insertList(annexCollect);
            }
        }
    }

    private void checkProj(EquipmentDto dto) {
        ProjPageReq req = new ProjPageReq();
        req.setOrgaId(dto.getOrgaId());
        List<Map<String, Object>> project = projectMapper.selectProject(req);
        if (project.size() != 1) {
            throw new BusinessException(500, "请选择项目!");
        }
        dto.setProjId((Long) project.get(0).get("projId"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int DelEquipment(List<Long> equipIds) {

        int iRet = equipmentMapper.deleteByIds(equipIds);

        Integer equipIsDel = equipmentMapper.getEquipIsDel(equipIds);
        if (equipIsDel != 0) {
            throw new BusinessException(-1, "设备下存在数据!,删除失败!");
        }

        if (iRet > 0) {
            //删除设备扩展信息
            equipextendMapper.deleteBatch(equipIds);
            //删除设备附件信息
            annexMapper.deleteByRecId(AnnexType.AnnexTypeEnum.mobilization.name(), equipIds);
        }
        return iRet;
    }

    @Override
    public List<Map<String, Object>> SelectEquipmentPage(Long userId, EquiPageReq dto) {
        //未选择项目，则查询所有管辖项目
        if (dto.getOrgaPathIds() == null) {
            //获取人员所属机构路径
            Map<String, Object> staffDto = staffMapper.selectStaffDetail(userId);
            String orgaPathIds = staffDto.get("orgaPathIds").toString();
            dto.setOrgaPathIds(orgaPathIds);
        }
        PageHelper.startPage(dto.getCurrPage(), dto.getPageSize());
        List<Map<String, Object>> list = equipmentMapper.selectEquiPageList(dto);
        list.forEach(equip -> {
            Integer equipSource = (Integer) equip.get("equipSource");
            List<DictionaryDto> source = dictionaryMapper.selectDic("设备来源", equipSource.toString());
            if (source.size() == 0) {
                equip.put("equipSource", "未知");
            } else {
                equip.put("equipSource", source.get(0).getDictName());
            }
        });

        return list;
    }

    @Override
    public List<ExecelEquipVos> SelectEquipmentPages(UserInfo userInfo, EquiPageReq dto) {
        //未选择项目，则查询所有管辖项目
        if (dto.getOrgaPathIds() == null) {
            //获取人员所属机构路径
            Map<String, Object> staffDto = staffMapper.selectStaffDetail(userInfo.getUserid());
            String orgaPathIds = staffDto.get("orgaPathIds").toString();
            dto.setOrgaPathIds(orgaPathIds);
        }
        List<ExecelEquipVos> list = equipmentMapper.selectEquiPageLists(dto);
//        list.forEach(equip -> {
//            Integer equipSource = equip.getEquipSource();
//            List<DictionaryDto> source = dictionaryMapper.selectDic("设备来源", equipSource.toString());
//            if (source.size() == 0) {
//                equip.put("equipSource", "未知");
//            } else {
//                equip.put("equipSource", source.get(0).getDictName());
//            }
//        });
        return list;
    }

    @Override
    public Map<String, Object> SelectEquipmentDetail(Long equipId) {
        Map<String, Object> equiDetail = equipmentMapper.selectEquiDetail(equipId);
        List<Long> orgaPathIds = Arrays.stream(equiDetail.get("orgaPathIds").toString().split("-")).map(map -> (Long.parseLong(map.trim()))).collect(Collectors.toList());
        equiDetail.put("orgaArr", orgaPathIds);
        List<Long> equipTypes = Arrays.stream(equiDetail.get("equipTypePath").toString().split("-")).map(map -> (Long.parseLong(map.trim()))).collect(Collectors.toList());
        equiDetail.put("equipTypeArr", equipTypes);
        List<AnnexDto> annexDtos = annexMapper.selectAllByRecId(AnnexType.AnnexTypeEnum.mobilization.name(), equipId);
        equiDetail.put("annexUrl", annexDtos.stream().map(AnnexDto::getAnnexUrl).collect(Collectors.toList()));
        return equiDetail;
    }

    public List<GetEquipList> GetEquipPage(EquipmentPageReq req) {
        PageHelper.startPage(req.getCurrPage(), req.getPageSize());

        return equipmentMapper.selectEquiPage(req);
    }

    @Override
    public List<GetEquipList> GetEquipList(EquipmentPageReq req) {
        return equipmentMapper.selectEquiPage(req);
    }

    @Override
    public List<ExcelEquipVo> getList(EquiPageReq req) {
        List<ExcelEquipVo> list = equipmentMapper.EquipmentRecExport(req);
        return list;
    }

    @Override
    public List<ExecelEquipVos> getLists(UserInfo userInfo,EquiPageReq req) {
        //未选择项目，则查询所有管辖项目
        if (req.getOrgaPathIds() == null) {
            //获取人员所属机构路径
            Map<String, Object> staffDto = staffMapper.selectStaffDetail(userInfo.getUserid());
            String orgaPathIds = staffDto.get("orgaPathIds").toString();
            req.setOrgaPathIds(orgaPathIds);
        }
        List<ExecelEquipVos> list = equipmentMapper.EquipmentRecExports(req);
        return list;
    }

    @Override
    public String getEquipNo(EquipNoDto dto) {

        //查到设备来源编码
        List<DictionaryDto> list = dictionaryMapper.selectDic("设备来源", dto.getEquipSourceId().toString());
        //查到设备类型编码
        EquipmenttypeEntity equipType = equipmenttypeMapper.selectByPrimaryKey(dto.getEquipTypeId());

        EquiPageReq req = new EquiPageReq();
        req.setEquipSource(dto.getEquipSourceId());
        req.setEquipTypeId(dto.getEquipTypeId().intValue());
        //查到该类型设备的最新的编号数
        List<Map<String, Object>> equips = equipmentMapper.selectEquiPageList(req);
        if (list.size() == 0 || equipType == null) {
            throw new BusinessException(-1, "获取异常!");
        }


        StringBuilder sb = new StringBuilder();
        DictionaryDto dic = list.get(0);
        sb.append(dic.getDictNote());
        //暂时使用设备类型id,之后改为编码
        sb.append(equipType.getEquipTypeId());

        //如果没查到该种设备的编号,则为第一条该类型设备的新增
        if (equips.size() == 0) {
            sb.append("0001");
        } else {
            Map<String, Object> equip = equips.get(0);
            if (equip.get("equipNo") == null) {
                throw new BusinessException(-1, "获取异常!该设备类型编码异常!");
            }
            String equipOldNo = equip.get("equipNo").toString();
            String equipNewNo = StringUtils.leftPad(String.valueOf(Integer.parseInt(equipOldNo.substring(equipOldNo.length() - 4)) + 1), 4, "0");

            sb.append(equipNewNo);
        }


        return sb.toString();
    }

    @Override
    public List<EquiPageReqModel> getEquipList(EquiPageReq equiPageReq) {
        List<EquiPageReqModel> list = equipmentMapper.queryList(equiPageReq);
        return list;
    }

    @Override
    public GenerateImportDto EquipmentRecImport(List<ExcelEquipVo> list) {
        //从jwt中获取当前的userid
        Long userId = 1L;
        //获取到userId传入Ordertils的方法中截取判断
        String projectNo = OrderUtils.getProjectNo(userId);
        //将获取到的projectNo放在redis中，当做key唯一值储存->唯一性,REDIS_ORDER = "keda:import:equipType_",项目编号
        String redisKey = OrderUtils.getRedisProjectNoKey(projectNo);
        String redisRecordCountKey = OrderUtils.getRedisRecordCountKey(projectNo);
        //3、存储到reids中，有效期为30分钟。
        Map<String, Object> RedisRecordMap = new HashMap<>(1);
        //首先设置返回的错误统计为0，设置一个参数
        int errorCount = 0;
        //reids的原子操作
        AtomicDouble totalAmount = new AtomicDouble();
        for (ExcelEquipVo vo : list) {
            //获取redis自增主键
            long id = redisUtils.incr(projectNo, 1);
            //4.验证 设备信息
            List<EquipmentDto> equipmentDtos = equipmentMapper.selectAllByEquipName(vo.getEquipName());
            if (equipmentDtos.size() > 0) {
                vo.setError(true);
                vo.setVerifyResult(vo.getEquipName()+"设备已存在");
            } else {
                vo.setError(false);
                List<String> rpList = list.stream().map(ExcelEquipVo::getEquipTypeName).collect(Collectors.toList());
                long count = rpList.stream().distinct().count();
                if (rpList.size() != count) {
                    vo.setError(true);
                    vo.setVerifyResult("设备" + vo.getEquipTypeName() + "的记录重复");
                }
                //2.项目验证
                ProjectDto projectDto = projectMapper.selectByProjName(vo.getProjName());
                if(projectDto==null){
                    vo.setError(true);
                    vo.setVerifyResult(vo.getProjName()+"项目不存在");
                }else {
                    vo.setError(false);
                    vo.setVerifyResult(null);
                    vo.setProjId(projectDto.getProjId());
                    vo.setOrgaId(projectDto.getOrgaId());
                }
            }
            redisUtils.addZset(redisRecordCountKey, String.valueOf(id), id);
            vo.setId(id);
            RedisRecordMap.put(String.valueOf(id), vo);

        }
        redisUtils.setHashMap(redisKey, RedisRecordMap, OrderUtils.ORDER_EXPIRE);
        //redisUtils.set(redisKey, list, OrderUtils.ORDER_EXPIRE);
        redisUtils.expire(redisRecordCountKey, OrderUtils.ORDER_EXPIRE);
        //统计数据
        GenerateImportDto dto = new GenerateImportDto();
        dto.setErrorCount(errorCount);
        dto.setProjectNo(projectNo);
        dto.setTotalAmount(BigDecimal.valueOf(totalAmount.get()));
        dto.setTotalCount(list.size());
        //缓存统计数据，避免保存数据时重复统计
        String statisticsKey = OrderUtils.getRedisStaticKey(projectNo);
        redisUtils.set(statisticsKey, dto, OrderUtils.ORDER_EXPIRE);
        return dto;
    }

    public List<Object> getEquipTypeListFromRedis(SaveImportReq req) {
        // 获取Redis中存储的值
        String projectNo = req.getProjectNo();
        String redisKey = OrderUtils.getRedisProjectNoKey(projectNo);
        String redisCountKey = OrderUtils.getCRedisCountKey(projectNo);
        Set<Object> ids = redisUtils.rangeZset(redisCountKey,0,1000);
        List<Object> list = redisUtils.multiGetHash(redisKey, ids);
        return list;

    }

    @Override
    public Map getWaitEquipmentListByPage(GetEquipImportReq req) {
        String projectNo = req.getProjectNo();
        Integer currentPage = req.getCurrPage();
        Integer pageSize = req.getPageSize();

        String redisKey = OrderUtils.getRedisProjectNoKey(projectNo);
        String redisCountKey = OrderUtils.getCRedisCountKey(projectNo);
        Long start = Long.valueOf((currentPage - 1) * pageSize);
        Long end = Long.valueOf(currentPage * pageSize - 1);
        Set<Object> ids = redisUtils.rangeZset(redisCountKey, start, end);
        List<Object> list = redisUtils.multiGetHash(redisKey, ids);

        List<ExcelEquipVo> rtnList = new ArrayList<>();
        for (Object obj : list) {
            JSONObject json = (JSONObject) JSONObject.toJSON(obj);
            String str = json.toString();//将json对象转换为字符串
            ExcelEquipVo dto = JSON.parseObject(str, ExcelEquipVo.class);
            rtnList.add(dto);
        }
        PageInfo<ExcelEquipVo> pageinfo = new PageInfo<>();
        pageinfo.setPageSize(req.getPageSize());
        pageinfo.setPageNum(req.getCurrPage());
        pageinfo.setList(rtnList);
        Map<Object, Object> maplist = redisUtils.getHashMap(redisKey);
        Integer totalSize = maplist.size();
        pageinfo.setPages(totalSize / req.getPageSize());
        pageinfo.setSize(totalSize);
        String redisStaticKey = OrderUtils.getRedisStaticKey(projectNo);
        GenerateImportDto staticDto = (GenerateImportDto) redisUtils.get(redisStaticKey);
        if (staticDto == null) {
            return null;
        }
        Map map = new HashMap();
        map.put("generateRechargeDto", staticDto);
        map.put("pageInfo", pageinfo);
        return map;
    }


    @Override
    public GenerateImportDto deliEquipmentRedis(DelEquipImportReq req) {
        String projectNo = req.getProjectNo();
        String redisKey = OrderUtils.getRedisProjectNoKey(projectNo);
        String redisCountKey = OrderUtils.getRedisRecordCountKey(projectNo);
        String redisStaticKey = OrderUtils.getRedisStaticKey(projectNo);
        Map<Object, Object> maplist = redisUtils.getHashMap(redisKey);
        Integer total = maplist.size();
        //取记录
        ExcelEquipVo delDto = (ExcelEquipVo) redisUtils.getHash(redisKey, req.getId().toString());
        //删除记录
        redisUtils.delHash(redisKey, req.getId().toString());
        redisUtils.removeZset(redisCountKey, req.getId().toString());
        //更新余额
        GenerateImportDto staticDto = (GenerateImportDto) redisUtils.get(redisStaticKey);
        if (staticDto == null) {
            return null;
        }
        staticDto.setTotalCount(total - 1);
        redisUtils.set(redisStaticKey, staticDto);
        return staticDto;
    }

    @Override
    public void insertExcelEquip(EquipmentDto record) {
        //record.setProjId(EquipmentEnum.PROJECT_ID.getValue());
        //record.setOrgaId(EquipmentEnum.ORGANIZATION_ID.getValue());
        record.setEquipTypeId(EquipmentEnum.EQUIPMENT_TYPE_ID.getValue());
        record.setEquipStatus(0);
        record.setCreateTime(LocalDateTime.now());
        equipmentMapper.insert(record);
        Long equipId = record.getEquipId();
        EquipextendEntity entity = new EquipextendEntity();
        entity.setEquipId(equipId);
        entity.setActQuitDate(record.getActQuitDate());
        equipextendMapper.insertSelective(entity);
    }

    @Override
    public GenerateImportDto updateImportEquip(UpdateImportEquipVo vo) {
        String redisKey = OrderUtils.getRedisProjectNoKey(vo.getProjectNo());
        String redisCountKey = OrderUtils.getRedisRecordCountKey(vo.getProjectNo());
        String redisStaticKey = OrderUtils.getRedisStaticKey(vo.getProjectNo());
        Map<Object, Object> maplist = redisUtils.getHashMap(redisKey);
        Integer total = maplist.size();

        //取记录
        ExcelEquipVo editDto = (ExcelEquipVo) redisUtils.getHash(redisKey, vo.getId().toString());
        if (editDto == null) {
            return null;
        }
        //编辑记录
        editDto.setEquipNo(vo.getEquipNo());
        editDto.setEquipName(vo.getEquipName());
        editDto.setEquipTypeName(vo.getEquipTypeName());
        editDto.setProjName(vo.getProjName());
        editDto.setEquipSource(vo.getEquipSource());
        Map<String, Object> map = new HashMap<>();
        map.put(vo.getId().toString(), editDto);
        redisUtils.setHashMap(redisKey, map);
        //TODO::验证记录
        GenerateImportDto staticDto = (GenerateImportDto) redisUtils.get(redisStaticKey);
        if (staticDto == null) {
            return null;
        }
        staticDto.setTotalCount(total);
        //更新项目信息
        redisUtils.set(redisStaticKey, staticDto, OrderUtils.ORDER_EXPIRE);
        return staticDto;
    }

    @Override
    public int equipmentBind(BindEquipmentReq dto) {
        EquipmentDto entity = new EquipmentDto();
        entity.setEquipId(dto.getEquipId());
        entity.setEquidTerminal(dto.getEquipSN());
        entity.setUpdateTime(LocalDateTime.now());
        return equipmentMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public String getEquipWxCode(WxCodeDto dto) throws Exception {
        EquipmentDto equipmentDto = equipmentMapper.selectWechatCode(dto.getEquipId());
        if (equipmentDto != null) {
            throw new BusinessException(-1, "该设备二维码已存在!");
        }

        //获取二维码
        InputStream wxCode = WeChatUtil.getWxCode(dto.getData());

        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        //图片存储文件夹路径
        String wxCodeImgeFilePath = "recwxCodeImage";
        String fileId = UUID.randomUUID().toString();
        //图片相对路径
        String filePath = (File.separator + wxCodeImgeFilePath + File.separator +fileId+"--"+dto.getEquipId() + ".jpg").replaceAll("\\\\", "/");

        //图片存储路径
        String fileSavePath = uploadDir + filePath;
        File imgFile = new File(uploadDir + wxCodeImgeFilePath);
        if (!imgFile.exists()) {
            imgFile.mkdirs();
        }

        //创建输出流
        FileOutputStream fileOutputStream = new FileOutputStream(fileSavePath, false);

        //图片绝对路径
        String fileRealPath = visitPath.concat(filePath);

        equipmentDto = new EquipmentDto();
        equipmentDto.setEquipId(dto.getEquipId());
        equipmentDto.setWechatCode(fileRealPath);
        equipmentMapper.updateByPrimaryKeySelective(equipmentDto);


        byte[] data = null;
        try {
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = wxCode.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
            //写入数据
            fileOutputStream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            swapStream.close();
            swapStream.flush();
            fileOutputStream.close();
            fileOutputStream.flush();
            if (wxCode != null) {
                try {
                    wxCode.close();
                } catch (IOException e) {
                    throw new Exception("输入流关闭异常");
                }
            }
        }

        //转换为base64
        String res = Base64.getEncoder().encodeToString(data);
        if (StringUtils.isNotBlank(res)) {
            String encoded = "data:image/jpg;base64," + res.replaceAll("[\\s*\t\n\r]", "");
            return encoded;
        }
        return null;
    }
}